package com.wkbb.sports.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.wkbb.common.base.BaseController;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.VersionConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.redis.RedisTemplateUtil;
import com.wkbb.sports.dto.*;
import com.wkbb.sports.enums.SportsModelTypeEnum;
import com.wkbb.sports.model.*;
import com.wkbb.sports.service.PracticeService;
import com.wkbb.sports.service.TrainService;
import com.wkbb.sports.utils.DateUtil;
import com.wkbb.sports.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@Api(description = "训练管理")
@RequestMapping("/sports/{apiVersion}/train")
@Slf4j
public class TrainController extends BaseController {

	@Autowired
	private TrainService trainService;

	@ApiOperation(value = "学生体质分析（各项目平均成绩）")
	@RequestMapping(value = "/getStuPhysicalAnalysis", method = RequestMethod.GET)
	public ResultDTO<PhysicalAnalysisDto> getStuPhysicalAnalysis(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学生id", required = true) @RequestParam(name = "studentId", required = true) String studentId)
	{
		UserDto userDto = this.getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		PhysicalAnalysisDto dto = trainService.getStuPhysicalAnalysis(studentId);
		if (dto == null) {
			dto = new PhysicalAnalysisDto();
		}
		dto.format();
		return new ResultDTO<>(dto);
	}

	@ApiOperation(value = "获取学生校内最近N天跳绳个人分析(默认30天)")
	@RequestMapping(value = "getLatelyStuSport", method = RequestMethod.GET)
	public ResultDTO<LatelStuSportDto> getLatelyStuSport(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学生id", required = true) @RequestParam(name = "studentId", required = true) String studentId,
			@ApiParam(value = "最近天数,默认30天", required = false,defaultValue = "30") @RequestParam(name = "day", required = false) Integer day){
		UserDto userDto = getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		Map<String, Object> params = new HashMap<>();
		params.put("studentId", studentId);
		//1小时内 心率异常 实时参与人数
		if (day == null || day == 0 ) day = 30;
		params.put("beginDate", DateUtil.addCurrDay(-day));
		params.put("endDate", DateUtil.getDate());
		return trainService.getLatelyStuSport(params);
	}

	@ApiOperation(value = "分页获取学生校内运动记录")
	@RequestMapping(value = "/getTrainListByStudent", method = RequestMethod.GET)
	public ResultDTO<?> getTrainListByStudent(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学生ID", required = true) @RequestParam(name = "studentId", required = true) Long studentId,
			@ApiParam(value = "项目类型ID") @RequestParam(name = "projectKind", required = false) Byte projectKind,
			@ApiParam(value = "类型(1训练 2比赛 3测评)") @RequestParam(name = "trainType", required = false) Byte trainType,
			@ApiParam(value = "分页数", defaultValue = "0") @RequestParam(name = "pageNo") int pageNo,
			@ApiParam(value = "分页大小", defaultValue = "20") @RequestParam(name = "pageSize") int pageSize){
		UserDto userDto = this.getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		Map<String, Object> params = new HashMap<>();
		params.put("studentId", studentId);
		params.put("projectKind", projectKind);
		params.put("trainType", trainType);
		try{
			PageInfo<TrainStuDto> pageInfo = trainService.getTrainListByStudent(params, pageNo, pageSize);
			return new ResultDTO<>(pageInfo);
		}catch(Throwable e) {
			logError(e);
			return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
		}
	}

	@ApiOperation(value = "获取学生校内运动记录详情")
	@RequestMapping(value = "/getTrainStudent", method = RequestMethod.GET)
	public ResultDTO<TrainStuDto> getTrainStudent(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "训练ID", required = true) @RequestParam(name = "trainId", required = true) Long trainId,
			@ApiParam(value = "学生ID", required = true) @RequestParam(name = "studentId", required = true) Long studentId){
		UserDto userDto = this.getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		Map<String, Object> params = new HashMap<>();
		params.put("trainId", trainId);
		params.put("studentId", studentId);
		try{
			TrainStuDto dto = trainService.getTrainStudent(params);
			return new ResultDTO<>(dto);
		}catch(Throwable e) {
			logError(e);
			return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
		}
	}

	@ApiOperation(value = "新增训练")
	@RequestMapping(value = "/addTrain", method = RequestMethod.POST)
	public ResultDTO<?> addTrain(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@RequestBody TrainDto train){
		log.info("addTrain(" + JSONObject.toJSONString(train) + ")");
		UserDto userDto = this.getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		train.setCreateBy(userDto.getName());
		HlifeTrain result;
		try{
			result = trainService.addTrain(train);
		}catch(Throwable e) {
			logError(e);
			return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
		}
		return new ResultDTO<HlifeTrain>(result);
	}
	
	@ApiOperation(value = "获取训练列表")
	@RequestMapping(value = "/queryTrainList", method = RequestMethod.GET)
	public ResultDTO<?> queryTrainList(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学校ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
			@ApiParam(value = "年级ID") @RequestParam(name = "gradeId", required = false) Long gradeId,
			@ApiParam(value = "班级ID") @RequestParam(name = "classId", required = false) Long classId,
			@ApiParam(value = "模式ID") @RequestParam(name = "modelType", required = false) Byte modelType,
			@ApiParam(value = "老师ID") @RequestParam(name = "teacherId", required = false) Long teacherId,
			@ApiParam(value = "项目类型ID") @RequestParam(name = "projectKind", required = false) Byte projectKind,
			@ApiParam(value = "类型(1训练 2比赛 3测评)") @RequestParam(name = "trainType", required = false) Byte trainType,
			@ApiParam(value = "分页数", defaultValue = "0") @RequestParam(name = "pageNo") int pageNo,
			@ApiParam(value = "分页大小", defaultValue = "20") @RequestParam(name = "pageSize") int pageSize){
		UserDto userDto = this.getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		Map<String, Object> params = new HashMap<>();
		if (orgId != 1) params.put("orgId", orgId);
		params.put("gradeId", gradeId);
		params.put("classId", classId);
		params.put("modelType", modelType);
		params.put("teacherId", teacherId);
		params.put("projectKind", projectKind);
		params.put("trainType", trainType);
		PageInfo<TrainDto> trains;
		try{
			trains = trainService.queryTrainList(params, pageNo, pageSize);
		}catch(Throwable e) {
			logError(e);
			return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
		}
		log.error("item count:" + trains.getSize());
		Map<String, List<TrainDto>> results = new TreeMap<>(new Comparator<String>() {
		    @Override
		    public int compare(String o1, String o2) {
		        return o2.compareTo(o1);
		    }
		});
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
		for(TrainDto train : trains.getList()) {
			String key = sdf.format(train.getStartTime());
			List<TrainDto> values = results.get(key);
			if(values == null) {
				values = new ArrayList<>();
				results.put(key, values);
			}
			values.add(train);
		}
		return new ResultDTO<Map<String, List<TrainDto>>>(results);
	}

	@ApiOperation(value = "获取训练列表")
	@RequestMapping(value = "/findTrainList", method = RequestMethod.GET)
	public ResultDTO<?> findTrainList(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学校ID", required = false) @RequestParam(name = "orgId", required = false) Long orgId,
			@ApiParam(value = "年级ID") @RequestParam(name = "gradeId", required = false) Long gradeId,
			@ApiParam(value = "班级ID") @RequestParam(name = "classId", required = false) Long classId,
			@ApiParam(value = "模式ID") @RequestParam(name = "modelType", required = false) Byte modelType,
			@ApiParam(value = "老师ID") @RequestParam(name = "teacherId", required = false) Long teacherId,
			@ApiParam(value = "项目类型ID") @RequestParam(name = "projectKind", required = false) Byte projectKind,
			@ApiParam(value = "类型(1训练 2比赛 3测评)") @RequestParam(name = "trainType", required = false) Byte trainType,
			@ApiParam(value = "分页数", defaultValue = "0") @RequestParam(name = "pageNo") int pageNo,
			@ApiParam(value = "分页大小", defaultValue = "20") @RequestParam(name = "pageSize") int pageSize){
//		log.info("queryTrainList(orgId:" + orgId + ", classId:" + classId + ", modelType:" + modelType
//				+ ", teacherId:" + teacherId + ", projectKind:" + projectKind + ", pageNo:" + pageNo + ", pageSize:" + pageSize + ")");
		UserDto userDto = this.getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		Map<String, Object> params = new HashMap<>();
		if (orgId != 1) params.put("orgId", orgId);
		params.put("gradeId", gradeId);
		params.put("classId", classId);
		params.put("modelType", modelType);
		params.put("teacherId", teacherId);
		params.put("projectKind", projectKind);
		params.put("trainType", trainType);
		PageInfo<TrainDto> trains;
		try{
			trains = trainService.queryTrainList(params, pageNo, pageSize);
		}catch(Throwable e) {
			logError(e);
			return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
		}
		return new ResultDTO<>(trains);
	}
	
	@ApiOperation(value = "获取单个训练详情")
	@RequestMapping(value = "/getTrain", method = RequestMethod.GET)
	public ResultDTO<?> getTrain(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "训练D", required = true) @RequestParam(name = "trainId", required = true) Long trainId){
		log.info("getTrain(trainId:" + trainId + ")");
		UserDto userDto = this.getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		TrainDto train;
		try{
			train = trainService.getTrain(trainId);
//			Map<String, Object> params = new HashMap<>();
//			params.put("trainId", trainId);
//			List<TrainStudentDto> students;
//			try{
//				students = trainService.queryTrainStudentList(params);
//			}catch(Throwable e) {
//				logError(e);
//				return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
//			}
//			train.setStudents(students);
			return new ResultDTO<>(train);
		}catch(Throwable e) {
			logError(e);
			return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
		}
	}
	
	@ApiOperation(value = "获取学生的训练信息")
	@RequestMapping(value = "/queryTrainStudentList", method = RequestMethod.GET)
	public ResultDTO<?> queryTrainStudentList(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
			@ApiParam(value = "年级ID", required = false) @RequestParam(name = "gradeId", required = false) Long gradeId,
			@ApiParam(value = "班级ID", required = false) @RequestParam(name = "classId", required = false) Long classId,
			@ApiParam(value = "训练ID", required = false) @RequestParam(name = "trainId", required = false) Long trainId,
			@ApiParam(value = "学生ID", required = false) @RequestParam(name = "studentId", required = false) Long studentId,
			@ApiParam(value = "学生姓名", required = false) @RequestParam(name = "studentName", required = false) String studentName,
			@ApiParam(value = "学号", required = false) @RequestParam(name = "studentNo", required = false) String studentNo,
			@ApiParam(value = "性别", required = false) @RequestParam(name = "sex", required = false) Byte sex,
			@ApiParam(value = "分页数", defaultValue = "0") @RequestParam(name = "pageNo") int pageNo,
			@ApiParam(value = "分页大小", defaultValue = "20") @RequestParam(name = "pageSize") int pageSize){
		log.info("queryTrainStudentList(orgId:" + orgId + ", gradeId:" + gradeId + "classId:"
			+ classId + ", trainId:" + trainId + ", studentId:" + studentId + ", pageNo:" + pageNo + ", pageSize:" + pageSize + ")");
		UserDto userDto = this.getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		Map<String, Object> params = new HashMap<>();
		params.put("orgId", orgId);
		params.put("gradeId", gradeId);
		params.put("classId", classId);
		params.put("trainId", trainId);
		params.put("studentId", studentId);
		params.put("studentNo", studentNo);
		params.put("studentName", studentName);
		params.put("sex", sex);
		PageInfo<TrainStudentDto> students;
		try{
			students = trainService.queryTrainStudentList4Persion(params, pageNo, pageSize);
		}catch(Throwable e) {
			logError(e);
			return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
		}
		return new ResultDTO<PageInfo<TrainStudentDto>>(students);
	}


	@ApiOperation(value = "获取学校设备信息")
	@RequestMapping(value = "/queryDeviceList", method = RequestMethod.GET)
	public ResultDTO<List<HlifeDevice>> queryDeviceList(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学校ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId){
		log.info("queryDeviceList(orgId:" + orgId + ")");
		UserDto userDto = this.getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		Map<String, Object> params = new HashMap<>();
		params.put("orgId", orgId);
		try{
			List<HlifeDevice> list = trainService.queryDeviceList(params);
			return new ResultDTO<>(list);
		}catch(Throwable e) {
			logError(e);
			return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
		}
	}

	@ApiOperation(value = "Pc端获取设备列表")
	@RequestMapping(value = "/getDevicePageList", method = RequestMethod.GET)
	public ResultDTO<PageInfo<HlifeDevice>> getDevicePageList(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学校ID", defaultValue = "1") @RequestParam(name = "orgId", required = true) Long orgId,
			@ApiParam(value = "设备名称", required = false) @RequestParam(name = "projectKind", required = false) Long projectKind,
			@ApiParam(value = "设备组别", required = false) @RequestParam(name = "groupName", required = false) String groupName,
			@ApiParam(value = "分页数", defaultValue = "1") @RequestParam(name = "pageNo") int pageNo,
			@ApiParam(value = "分页大小", defaultValue = "10") @RequestParam(name = "pageSize") int pageSize){
		log.info("queryDeviceList(orgId:" + orgId + ")");
		UserDto userDto = this.getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		Map<String, Object> params = new HashMap<>();
		params.put("orgId", orgId);
		params.put("projectKind", projectKind);
		params.put("groupName", groupName);
		try{
			PageInfo<HlifeDevice> list = trainService.getDevicePageList(params,pageNo,pageSize);
			return new ResultDTO<>(list);
		}catch(Throwable e) {
			logError(e);
			return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
		}
	}

	@ApiOperation(value = "启用禁用设备")
	@RequestMapping(value = "/changeDeviceStatus", method = RequestMethod.POST)
	public ResultDTO<?> changeDeviceStatus(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "设备ID", required = true) @RequestParam(name = "id", required = true) Long id,
			@ApiParam(value = "状态", required = true) @RequestParam(name = "status", required = true) Integer status){
		UserDto userDto = this.getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		try{
			trainService.changeDeviceStatus(id,status);
			return new ResultDTO<>();
		}catch(Throwable e) {
			logError(e);
			return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
		}
	}
	
	@ApiOperation(value = "批量修改设备")
	@RequestMapping(value = "/batchModifyDevices", method = RequestMethod.POST)
	public ResultDTO<?> batchModifyDevices(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@RequestBody List<DeviceDto> devices){
		log.info("batchModifyDevices(" + JSONObject.toJSONString(devices) + ")");
		UserDto userDto = this.getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		for(DeviceDto dev : devices) {
			dev.setCreateUser(userDto.getName());
			dev.setUpdateUser(userDto.getName());
		}
		try{
			int count = trainService.modifyDevices(devices);
			if (count == 0) return new ResultDTO<>(ErrorCode.DEVICE_NOT_EXISTS);
		}catch(Throwable e) {
			logError(e);
			return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
		}
		return new ResultDTO<List<?>>(devices);
	}

	@ApiOperation(value = "获取学生训练详情")
	@RequestMapping(value = "/getStudentTrainInfo", method = RequestMethod.GET)
	public ResultDTO<?> getStudentTrain(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "训练ID", required = true) @RequestParam(name = "trainId", required = true) Long trainId,
			@ApiParam(value = "学生ID", required = true) @RequestParam(name = "studentId", required = true) Long studentId
			){
		log.info("getStudentTrainInfo(trainId:" + trainId + ", studentId:" + studentId + ")");
		UserDto userDto = this.getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		StudentTrainInfoDto studentTrainInfo;
		try{
			studentTrainInfo = trainService.getStudentTrainInfo(trainId, studentId);
		}catch(Throwable e) {
			logError(e);
			return new ResultDTO<>(ErrorCode.SYSTEM_ERROR);
		}
		return new ResultDTO<StudentTrainInfoDto>(studentTrainInfo);
	}

	@ApiOperation(value = "老师训练整体统计")
	@RequestMapping(value = "/getTeacherTrainWholeStat", method = RequestMethod.GET)
	public ResultDTO<Map<String,Object>> getTeacherTrainWholeStat(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId)
	{
		log.info("getTeacherTrainWholeStat orgId:{}",orgId);

		try {

			UserDto userDto = this.getUserByLogin();
			if(null == userDto) {
				return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
			}

			Map<String,Object> map = trainService.getTeacherTrainWholeStat(orgId,userDto.getId());

			return new ResultDTO<Map<String,Object>>(map);

		} catch (Exception e) {
			log.error("***********getTeacherTrainWholeStat******", e);
			return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
		}
	}

	@ApiOperation(value = "老师训练统计")
	@RequestMapping(value = "/getTeacherTrainStat", method = RequestMethod.GET)
	public ResultDTO<Map<String,Object>> getTeacherTrainStat(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
			@ApiParam(value = "项目类型", required = true) @RequestParam(name = "projectKind", required = true) Integer projectKind)
	{
		log.info("getTeacherTrainStat orgId:{} projectKind:{}",orgId, projectKind);

		try {

			UserDto userDto = this.getUserByLogin();
			if(null == userDto) {
				return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
			}

			Map<String,Object> map = trainService.getTeacherTrainStat(orgId,userDto.getId(),projectKind);

			return new ResultDTO<Map<String,Object>>(map);

		} catch (Exception e) {
			log.error("***********getTeacherTrainWholeStat******", e);
			return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
		}
	}

	@ApiOperation(value = "老师训练成绩不及格分页列表")
	@RequestMapping(value = "/getTeacherTrainFlunkStudentPageList", method = RequestMethod.GET)
	public ResultDTO<PageInfo<TrainStudentDto>> getTeacherTrainFlunkStudentPageList(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
			@ApiParam(value = "班级ID", required = false) @RequestParam(name = "classId", required = false) Long classId,
			@ApiParam(value = "项目ID", required = false) @RequestParam(name = "projectKind", required = false) Integer projectKind,
			@ApiParam(value = "开始日期", required = true) @RequestParam(name = "beginDate", required = true) String beginDate,
			@ApiParam(value = "结束日期", required = true) @RequestParam(name = "endDate", required = true) String endDate,
			@ApiParam(value = "页码", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo,
			@ApiParam(value = "每页条数", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize
			)
	{
		log.info("getTeacherTrainFlunkStudentPageList orgId:{} projectKind:{} beginDate:{} endDate:{}",orgId, projectKind, beginDate, endDate);

		try {

			UserDto userDto = this.getUserByLogin();
			if(null == userDto) {
				return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
			}

			return new ResultDTO<>(trainService.getTrainFlunkStudentPageList(orgId,classId,projectKind,beginDate,endDate,pageNo,pageSize));

		} catch (Exception e) {
			log.error("***********getTeacherTrainFlunkStudentPageList******", e);
			return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
		}
	}

	@ApiOperation(value = "学生训练分析")
	@RequestMapping(value = "/getTeacherTrainStudentReport", method = RequestMethod.GET)
	public ResultDTO<Map<String,Object>> getTeacherTrainStudentReport(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学校ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
			@ApiParam(value = "学生ID", required = true) @RequestParam(name = "studentId", required = true) Long studentId,
			@ApiParam(value = "项目ID", required = true) @RequestParam(name = "projectKind", required = true) Integer projectKind,
			@ApiParam(value = "开始日期", required = true) @RequestParam(name = "beginDate", required = true) String beginDate,
			@ApiParam(value = "结束日期", required = true) @RequestParam(name = "endDate", required = true) String endDate)
	{
		log.info("*****getTeacherTrainStudentReport orgId:{} studentId:{} beginDate:{} endDate:{}*****",orgId,studentId,beginDate,endDate);
		try {
			Map<String,Object> reMap = trainService.getTeacherTrainStudentReport(orgId,studentId,projectKind,beginDate,endDate);
			return new ResultDTO<>(reMap);
		}catch (Exception e){
			log.error("***********getTeacherTrainStudentReport******", e);
			return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
		}
	}

	@ApiOperation(value = "学生训练分析")
	@RequestMapping(value = "/getTrainStudentReport", method = RequestMethod.GET)
	public ResultDTO<Map<String,Object>> getTrainStudentReport(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学校ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
			@ApiParam(value = "学生ID", required = true) @RequestParam(name = "studentId", required = true) Long studentId,
			@ApiParam(value = "项目ID", required = true) @RequestParam(name = "projectKind", required = true) Integer projectKind)
	{
		try {
			String beginDate = DateUtil.rollDate(Calendar.getInstance(),Calendar.MONTH, -2);
			String endDate = DateUtil.getDate();
//			log.info("*****getTrainStudentReport beginDate:{} endDate:{} *****",beginDate,endDate);
			Map<String,Object> reMap = trainService.getTrainStudentReport(orgId,studentId,projectKind,beginDate,endDate);
			return new ResultDTO<>(reMap);
		}catch (Exception e){
			log.error("***********getTeacherTrainStudentReport******", e);
			return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
		}
	}

	@ApiOperation(value = "体育训练报告(家长)")
	@RequestMapping(value = "/getSportsReportToFamily", method = RequestMethod.GET)
	public ResultDTO<Map<String,Object>> getSportsReportToFamily(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "学校ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
			@ApiParam(value = "用户ID", required = true) @RequestParam(name = "userId", required = true) Long userId,
			@ApiParam(value = "项目ID", required = true) @RequestParam(name = "projectId", required = true) Long projectId,
			@ApiParam(value = "训练日期", required = true) @RequestParam(name = "trainDate", required = true) String trainDate)
	{
		log.info("*****getSportsReportToFamily orgId:{} userId:{} projectId:{} trainDate:{}*****",orgId,userId,projectId,trainDate);
		try {
			Map<String,Object> reMap = trainService.getSportsReportToFamily(orgId,userId,trainDate,projectId);
			return new ResultDTO<>(reMap);
		}catch (Exception e){
			log.error("***********getSportsReportToFamily******", e);
			return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
		}
	}

	@ApiOperation(value = "批量授权设备")
	@RequestMapping(value = "/authorizationDevices", method = RequestMethod.POST)
	public ResultDTO<HlifeDeviceAuthorizationLog> authorizationDevices(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "设备类型", required = true) @RequestParam(name = "projectKind", required = true) Byte projectKind,
			@ApiParam(value = "设备列表", required = true) @RequestParam(name = "devices", required = true) String devices){
		UserDto userDto = this.getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		HlifeDeviceAuthorizationLog deviceAuthorizationLog = new HlifeDeviceAuthorizationLog();
		deviceAuthorizationLog.setUniqueId(DateUtil.getTodayyyyyMMdd()+ RandomUtil.generateNumber(6));
		deviceAuthorizationLog.setProjectKind(projectKind);
//		deviceAuthorizationLog.setCreateUser("刘志鹏");
		deviceAuthorizationLog.setCreateUser(userDto.getName());
		deviceAuthorizationLog = trainService.authorizationDevices(deviceAuthorizationLog,devices);
		if (deviceAuthorizationLog.getId() == null){
			return new ResultDTO<>(false,"1000001","授权失败，当前选中设备列表已被授权过");
		}
		ResultDTO<HlifeDeviceAuthorizationLog> resultDTO = new ResultDTO<>(deviceAuthorizationLog);
//		resultDTO.setErrorMsg("成功授权设备"+deviceAuthorizationLog.getDeviceCount()+"个");
		return resultDTO;
	}

	@ApiOperation(value = "授权设备操作日志列表")
	@RequestMapping(value = "/queryDeviceAuthorizationLogList", method = RequestMethod.GET)
	public ResultDTO<?> queryDeviceAuthorizationLogList(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "设备类型", required = false) @RequestParam(name = "projectKind", required = false) Byte projectKind,
			@ApiParam(value = "分页数", defaultValue = "1") @RequestParam(name = "pageNo") int pageNo,
			@ApiParam(value = "分页大小", defaultValue = "20") @RequestParam(name = "pageSize") int pageSize){
		UserDto userDto = this.getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		PageInfo<HlifeDeviceAuthorizationLog> list = trainService.queryDeviceAuthorizationLogList(projectKind,pageNo,pageSize);
		return new ResultDTO<>(list);
	}

	@ApiOperation(value = "已授权设备总数")
	@RequestMapping(value = "/getDeviceAuthorizationCount", method = RequestMethod.GET)
	public ResultDTO<?> getDeviceAuthorizationCount(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion){
		List<HlifeDeviceAuthorizationLog> list = trainService.getDeviceAuthorizationCount();
		return new ResultDTO<>(list);
	}

	@ApiOperation(value = "平板申请授权")
	@RequestMapping(value = "/applyPadAuthorization", method = RequestMethod.POST)
	public ResultDTO<?> applyPadAuthorization(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@RequestBody HlifePadAuthorizationLog padAuthorizationLog){
		UserDto userDto = this.getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		padAuthorizationLog.setCreateUser(userDto.getName());
//		padAuthorizationLog.setCreateUser("刘志鹏");
		padAuthorizationLog.setStatus((byte) 1);
		int result = trainService.applyPadAuthorization(padAuthorizationLog);
		if (result > 0) return new ResultDTO<>();
		return new ResultDTO<>(ErrorCode.SYSTEM_REPEAT);
	}

	@ApiOperation(value = "平板授权状态")
	@RequestMapping(value = "/getPadAuthorizationStatus", method = RequestMethod.GET)
	public ResultDTO<HlifePadAuthorizationLog> getPadAuthorizationStatus(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "设备id", required = true) @RequestParam(name = "padId", required = true) String padId){
		HlifePadAuthorizationLog data = trainService.getPadAuthorizationStatus(padId);
		return new ResultDTO<>(data);
	}

	@ApiOperation(value = "平板授权申请列表")
	@RequestMapping(value = "/queryPadAuthorizationLogList", method = RequestMethod.GET)
	public ResultDTO<?> queryPadAuthorizationLogList(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "平板id", required = false) @RequestParam(name = "padId", required = false) String padId,
			@ApiParam(value = "分页数", defaultValue = "1") @RequestParam(name = "pageNo") int pageNo,
			@ApiParam(value = "分页大小", defaultValue = "20") @RequestParam(name = "pageSize") int pageSize){
		UserDto userDto = this.getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		PageInfo<HlifePadAuthorizationLog> list = trainService.queryPadAuthorizationLogList(padId,pageNo,pageSize);
		return new ResultDTO<>(list);
	}

	@ApiOperation(value = "已授权硬件列表")
	@RequestMapping(value = "/queryDeviceAuthorizationList", method = RequestMethod.GET)
	public ResultDTO<?> queryDeviceAuthorizationList(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "项目类型", required = false) @RequestParam(name = "projectKind", required = false) Integer projectKind,
			@ApiParam(value = "分页数", defaultValue = "1") @RequestParam(name = "pageNo") int pageNo,
			@ApiParam(value = "分页大小", defaultValue = "20") @RequestParam(name = "pageSize") int pageSize){
		UserDto userDto = this.getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		PageInfo<HlifeDeviceAuthorization> list = trainService.queryDeviceAuthorizationList(projectKind,pageNo,pageSize);
		return new ResultDTO<>(list);
	}

	@ApiOperation(value = "平板授权审核")
	@RequestMapping(value = "/auditPadAuthorization", method = RequestMethod.POST)
	public ResultDTO<HlifePadAuthorizationLog> auditPadAuthorization(
			@ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
			@ApiParam(value = "id", required = true) @RequestParam(name = "id", required = true) Long id,
			@ApiParam(value = "状态(1申请中、2通过申请、3拒绝)", required = true) @RequestParam(name = "status", required = true) Byte status){
		UserDto userDto = getUserByLogin();
		if(null == userDto) {
			return new ResultDTO<>(ErrorCode.SECURITY_ACCESS_TOKEN_NOT_EXIST);
		}
		String userName = userDto.getName();
//		String userName = "刘志鹏";
		int result = trainService.auditPadAuthorization(id,status,userName);
		if (result > 0) return new ResultDTO<>();
		return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
	}


	private void logError(Throwable e) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		e.printStackTrace(pw);
		pw.flush();
		log.error(sw.toString());
	}
}
